import sys
sys.path.append(sys.path[0] + "/interpreter")
sys.path.append(sys.path[0] + "/LLVM")
sys.path.append(sys.path[0] + "/parser")
sys.path.append(sys.path[0] + "/parser/ply-2.5/")
from functionBinding import functionBinding
from functionDef import functionDef
from application import application
from Return import Return
from builtin import *
from varRef import varRef
from jsobject import *
from interpreter import interpreter
from endvals import *
from objectOps import *
from sequence import *
from conditionals import *
from sequence import *
from varBinding import *
from varMut import *
from customExceptions import *
from scope import scope

from astToLLVM import astToLLVM
from Footle_Parser import *
from llvmhelper import *
from StaticPass import *


import os

class compileFootleFile:
	def __init__(self):
		in_file = None
		if(len(sys.argv) > 1):
			in_file = open(sys.argv[1],"r")
		if(in_file == None):
			sys.stderr.write( "No file inputted\n")
			return
		self.code = in_file.read()
		self.parser = parserClass(self.code)
		self.helper = llvmHelper()
		self.outputFile = "output.s"

		in_file.close()


	
	def run(self):
		generatedAST =	self.parser.parse()
#		print "Generated AST:\n" + str(generatedAST)
#		print "\n ----------------------------------------------------\n"
		test = astToLLVM(generatedAST, False, False)
		outfile =  open(self.outputFile,"w")
		outfile.writelines(test.outputLLVM())
		outfile.close()

		
		os.system("llvm-gcc ./LLVM/llvmerrors.c -c -emit-llvm -o llvmerrors.o")
		os.system("llvm-gcc ./LLVM/utilityFunctions.c -c -emit-llvm -o utilityFunctions.o")
		os.system("llvm-as -f " + self.outputFile)
		os.system("llvm-ld "+self.outputFile+".bc llvmerrors.o utilityFunctions.o -o a.out")

		print "\nCode is compiled into a.out\n"

		#print "\n" + self.helper.getDispatch()
		
		#interp = interpreter(generatedAST)
		#print "\nInterpreted answer: ",interp.execute()
	
	def getErrorStr(self):
		return "Prog: " + str(self.prog) + "\nExpected: " + str(self.aststr) + "\nFound: "  + str(self.generatedASTstr) + "\n"
		
if __name__ == "__main__":
	test = compileFootleFile()
	test.run()
